package time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

public class TimeUtil {
    /**
     * 枚举类
     */
    public enum DateUnit {
        YEAR("year"),
        MONTH("month"),
        DAY("day");

        private String unit;

        DateUnit(String unit) {
            this.unit = unit;
        }

        public String getUnit() {
            return this.unit;
        }
    }

    /**
     * 获取两个日期字符串之间的所有年份/月份/天（左闭右闭）
     *
     * @param startDateStr  yyyyMMdd
     * @param endDateStr    yyyyMMdd
     * @param dateUnit
     * @return
     */
    public static List<String> getDateStrBetween(String startDateStr, String endDateStr, DateUnit dateUnit) {
        List<String> result = new ArrayList<>();
        SimpleDateFormat sdf;
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();

        try {
            sdf = new SimpleDateFormat("yyyyMMdd");
            start.setTime(sdf.parse(startDateStr));
            end.setTime(sdf.parse(endDateStr));
//            end.add(Calendar.DAY_OF_MONTH,-1); // end往前减1天，处理20210101这种情况（实现左闭右开）
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar curr = start;

        switch (dateUnit) {
            case YEAR:
                sdf = new SimpleDateFormat("yyyy");
                while (curr.before(end)) {
                    result.add(sdf.format(curr.getTime()));
                    curr.add(Calendar.YEAR, 1);
                }
                break;
            case MONTH:
                sdf = new SimpleDateFormat("yyyyMM");
                while (curr.before(end)) {
                    result.add(sdf.format(curr.getTime()));
                    curr.add(Calendar.MONTH, 1);
                }
                break;
            case DAY:
                sdf = new SimpleDateFormat("yyyyMMdd");
                while (curr.before(end)) {
                    result.add(sdf.format(curr.getTime()));
                    curr.add(Calendar.DAY_OF_MONTH, 1);
                }
                break;
            default:
                sdf = new SimpleDateFormat("yyyy");
                while (curr.before(end)) {
                    result.add(sdf.format(curr.getTime()));
                    curr.add(Calendar.YEAR, 1);
                }
                break;
        }

        // 最后要加上 endDateStr 所属的年份/月份/天（保证不漏）
        result.add(sdf.format(end.getTime()));
        return result.stream().distinct().collect(Collectors.toList());
    }

    public static void main(String[] args) {
        System.out.println(getDateStrBetween("20240201", "20240402", DateUnit.DAY));
    }
}
